package club.kingyin.kyblogprocore.controller;


import club.kingyin.commons.clients.UserClient;
import club.kingyin.commons.constant.AuthorizeConstant;
import club.kingyin.commons.entity.core.Comment;
import club.kingyin.commons.entity.core.Document;
import club.kingyin.commons.entity.user.Message;
import club.kingyin.commons.enums.BlogEnum;
import club.kingyin.commons.response.Result;
import club.kingyin.easycache.annotation.EasyCache;
import club.kingyin.kyblogprocore.dao.CommentDao;
import club.kingyin.kyblogprocore.dao.DocumentDao;
import club.kingyin.kyblogprocore.entity.CommentPram;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import club.kingyin.kyblogprocore.service.CommentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;

/**
 * (Comment)表控制层
 *
 * @author makejava
 * @since 2022-02-16 18:20:32
 */
@RestController
@RequestMapping("comment")
public class CommentController{
    /**
     * 服务对象
     */
    @Resource
    private CommentService commentService;

    @Resource
    private CommentDao commentDao;

    @Resource
    private UserClient userClient;

    @Resource
    private DocumentDao documentDao;

    /**
     * 分页查询所有数据
     *
     * @param pram    分页对象
     * @return 所有数据
     */
    @PostMapping("/all")
    public Result selectAll(@RequestHeader(AuthorizeConstant.ROLE) String role,
            @RequestBody CommentPram pram) throws UnsupportedEncodingException {
        switch (Objects.requireNonNull(BlogEnum.deBlogEnum(URLDecoder.decode(role, "UTF8")))) {
            case ADMIN:
            case ROOT:
                return Result.success(this.commentService.page(pram.getPage(), new LambdaQueryWrapper<>(pram.getComment()).orderByDesc(Comment::getTimestamp)));
            default: return Result.failR("无操作权限");
        }
    }

//    /**
//     * 通过主键查询单条数据
//     *
//     * @param id 主键
//     * @return 单条数据
//     */
//    @GetMapping("{id}")
//    public Result selectOne(@PathVariable Serializable id) {
//        return Result.success(this.commentService.getById(id));
//    }

    /**
     * 新增数据
     *
     * @param comment 实体对象
     * @return 新增结果
     */
    @EasyCache(prams = {"userid"},delete = {"commentsByUserid"}, module = "ky-core")
    @EasyCache(prams = {"comment.objectid"},delete = {"comments"}, module = "ky-core")
    @PostMapping("/save")
    public Result insert(@RequestHeader(AuthorizeConstant.ID) int userid,@RequestHeader(AuthorizeConstant.NICKNAME) String nickname,
                         @RequestHeader(AuthorizeConstant.AVATAR) String avatar,
                         @RequestBody Comment comment) throws UnsupportedEncodingException {
        comment.setUserid(userid);
        long timestamp = System.currentTimeMillis();
        comment.setTimestamp(timestamp);
        comment.setStatus(BlogEnum.NORMAL);
        if(comment.getParentid() != null) {
            LambdaUpdateWrapper<Comment> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(Comment::getId,comment.getParentid()).setSql("size = size + 1");
            commentDao.update(null,updateWrapper);
        }
        Document document = null;
        if (comment.getReplaceid() == null) {
            LambdaQueryWrapper<Document> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.select(Document::getUserid,Document::getTitle).eq(Document::getId,comment.getObjectid());
            document = documentDao.selectOne(queryWrapper);
        }
        boolean save = this.commentService.save(comment);
        if (save && userid != (comment.getReplaceid()==null? Objects.requireNonNull(document).getUserid():comment.getReplaceid())) {
            // 评论成功并且不是评论的自己的文章，评论
            Message message = new Message();
            nickname = URLDecoder.decode(nickname,"UTF8");
            message.setUserid(comment.getReplaceid());
            message.setTimestamp(timestamp);
            // 这里是文章id
            message.setObjectid(comment.getObjectid());
            message.setStatus(BlogEnum.UNREAD);
            message.setAvatar(URLDecoder.decode(avatar,"UTF8"));
            if (comment.getReplaceid() == null) {
                // 评论的是文章
                message.setUserid(document.getUserid());
                message.setData("【"+nickname+"】评论了你的文章【"+document.getTitle()+"】："+comment.getContent());
            } else {
                message.setUserid(comment.getReplaceid());
                message.setData("【"+nickname+"】回复了你："+comment.getContent());
            }
            userClient.sentMessage(message);
        }
        return save?Result.infoN("评论成功"):Result.failR("评论失败");
    }

    @EasyCache(prams = {"commentPram.comment.objectid","commentPram.page.current","commentPram.page.size","commentPram.comment.parentid"}, module = "ky-core")
    @PostMapping("/list")
    public Result comments(@RequestBody CommentPram commentPram) {
        return Result.success(commentService.selectComments(commentPram.getPage(), commentPram.getComment()));
    }

    @EasyCache(prams = {"commentPram.comment.userid","commentPram.page.current","commentPram.page.size"},module = "ky-core")
    @PostMapping("/pages")
    public Result commentsByUserid(@RequestBody CommentPram commentPram) {
        LambdaQueryWrapper<Comment> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Comment::getUserid,commentPram.getComment().getUserid()).orderByDesc(Comment::getTimestamp);
        return Result.success(commentDao.selectPage(commentPram.getPage(),queryWrapper));
    }

    @EasyCache(prams = {"userid"},delete = {"commentsByUserid"}, module = "ky-core")
    @EasyCache(prams = {"objectid"},delete = {"comments"}, module = "ky-core")
    @GetMapping("/delete")
    public Result removeComment(@RequestHeader(AuthorizeConstant.ID) int userid,
                                @RequestHeader(AuthorizeConstant.ROLE) String role,
                                @RequestParam("id") int id,@RequestParam("objectid") int objectid) throws UnsupportedEncodingException {
        LambdaQueryWrapper<Comment> queryWrapper = Wrappers.lambdaQuery();
        switch (Objects.requireNonNull(BlogEnum.deBlogEnum(URLDecoder.decode(role, "UTF8")))) {
            case ADMIN:
            case ROOT:
                queryWrapper.eq(Comment::getId,id);
                break;
            default: queryWrapper.eq(Comment::getUserid,userid).eq(Comment::getId,id);

        }
        Comment comment = commentDao.selectById(id);
        int delete = commentDao.delete(queryWrapper);
        if(comment.getParentid() != null) {
            LambdaUpdateWrapper<Comment> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(Comment::getId,comment.getParentid()).setSql("size = size - "+delete);
            commentDao.update(null,updateWrapper);
        }
        return delete > 0?Result.infoN("删除成功"):Result.failR("删除失败");
    }

//    /**
//     * 删除数据
//     *
//     * @param idList 主键结合
//     * @return 删除结果
//     */
//    @DeleteMapping
//    public Result delete(@RequestParam("idList") List<Long> idList) {
//        return Result.success(this.commentService.removeByIds(idList));
//    }
}

